﻿using System.IO;
using System.Net;
using System.Text;
using System.Configuration;
using System.Web;

namespace Xpus.YouYTube.Utility
{
	/// <summary>
	/// 提供ReCaptcha验证。
	/// </summary>
	public class TReCaptcha
	{
		const string ReCaptchaPrivateKey = "recaptcha.privatekey";
		const string ReCaptchaPublicKey = "recaptcha.publickey";
		const string ServiceUrl = "http://api-verify.recaptcha.net/verify";

		/// <summary>
		/// 获取Private Key。
		/// </summary>
		public static string PrivateKey
		{
			get { return ConfigurationManager.AppSettings[ReCaptchaPrivateKey]; }
		}

		/// <summary>
		/// 获取Public Key。
		/// </summary>
		public static string PublicKey
		{
			get { return ConfigurationManager.AppSettings[ReCaptchaPublicKey]; }
		}

		/// <summary>
		/// 进行服务器端验证。
		/// </summary>
		/// <param name="challenge">客户端返回的recaptcha_challenge_field。</param>
		/// <param name="response">客户端返回的recaptcha_challenge_field。</param>
		/// <returns></returns>
		public static bool Verify(string challenge, string response)
		{
			try
			{
				string ip = HttpContext.Current.Request.UserHostAddress;

				string content = string.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",
					HttpUtility.UrlEncode(PrivateKey),
					HttpUtility.UrlEncode(ip),
					HttpUtility.UrlEncode(challenge),
					HttpUtility.UrlEncode(response));
				byte[] contentbs = Encoding.ASCII.GetBytes(content);

				HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServiceUrl);
				request.Method = "POST";
				request.ProtocolVersion = HttpVersion.Version10;
				request.Timeout = 30 * 1000;
				request.UserAgent = "reCAPTCHA/ASP.NET";
				request.ContentType = "application/x-www-form-urlencoded";

				using (Stream s = request.GetRequestStream())
				{
					s.Write(contentbs, 0, contentbs.Length);
				}

				HttpWebResponse res = (HttpWebResponse)request.GetResponse();
				using (StreamReader sr = new StreamReader(res.GetResponseStream()))
				{
					string resultLine = sr.ReadLine();

					return resultLine == "true";
				}
			}
			catch
			{
				return false;
			}
		}
	}
}
